package com.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * scattering: 分散。将数据分散写入到buffer数组，依次写入
 * gathering：聚合。从buffer数组中读取数据，依次读
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //启用serverSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 启用监听端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        // 建立绑定关系
        serverSocketChannel.socket().bind(inetSocketAddress);
        // buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;
        while (true){
            int byteRead = 0;
            while (byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead:"+byteRead);
                Arrays.stream(byteBuffers).map(byteBuffer -> "position:" + byteBuffer.position() + ",limit:" + byteBuffer.limit()).forEach(System.out::println);
            }

            Arrays.stream(byteBuffers).forEach(Buffer::flip);

            // 将数据读出，显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long write = socketChannel.write(byteBuffers);
                byteWrite += write;
            }

            // 将所有的buffer 进行clear
            Arrays.stream(byteBuffers).forEach(Buffer::clear);

            System.out.println("byteRead:"+byteRead+",byteWrite:"+byteWrite+",messageLength:"+messageLength);
        }

    }
}
